package primetest.impl.controler;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;

import org.primefaces.event.RowEditEvent;


import primetest.dto.TermDto;
import primetest.impl.dictionary.Dictionary;

@Named("dictionaryControler")
@SessionScoped
public class DictionaryControler implements Serializable {

	private static final long serialVersionUID = -1903186271970239627L;

	@Inject
	private Dictionary dictionary;

	private List<TermDto> list;
	private List<TermDto> filteredTerms;

	public DictionaryControler() {

	}

	public Map<String, String> getDictionary() {
		return (Map<String, String>) dictionary;
	}

	public void reset() {
		dictionary.clear();
	}

	public List<TermDto> getTermList() {
		if (list == null) {
			list = new ArrayList<TermDto>();
			for (Entry<String, String> e : dictionary.entrySet()) {
				list.add(new TermDto(e.getKey(), e.getValue()));
			}
			Collections.sort(list, new Comparator<TermDto>() {
				@Override
				public int compare(TermDto a, TermDto b) {
					return a.getKey().compareToIgnoreCase(b.getKey());
				}
			});
		}
		return list;
	}

	public void onEdit(RowEditEvent event) {
		TermDto e = (TermDto) event.getObject();
		FacesMessage msg = new FacesMessage("Glossary Edited", e.getKey());
		dictionary.put(e.getKey(), e.getValue());
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public void onCancel(RowEditEvent event) {
		FacesMessage msg = new FacesMessage("Glossary Cancelled",
				((TermDto) event.getObject()).getKey());
		FacesContext.getCurrentInstance().addMessage(null, msg);
	}

	public List<TermDto> getFilteredTerms() {
		return filteredTerms;
	}

	public void setFilteredTerms(List<TermDto> filteredTerms) {
		this.filteredTerms = filteredTerms;
	}

}
